package com.jule.teenpatti.game.network.protocol.reqs;

import JoloProtobuf.GameSvr.JoloGame;
import com.google.common.primitives.Ints;
import com.jule.teenpatti.game.gameUtil.GameLogic;
import com.jule.teenpatti.game.model.PlayerInfo;
import com.jule.teenpatti.game.model.eenum.NextBetPlayerReasonEnum;
import com.jule.teenpatti.game.model.eenum.PlayerStateEnum;
import com.jule.teenpatti.game.network.protocol.ClientReq;
import com.jule.teenpatti.game.network.protocol.acks.JoloGame_ApplySeeCardAck_50006;
import com.jule.teenpatti.game.network.protocol.acks.JoloGame_FullPressureShowAck_50065;
import com.jule.teenpatti.game.network.protocol.acks.JoloGame_GamePrepareAck_50064;
import com.jule.teenpatti.game.play.AbstractTable;
import com.jule.teenpatti.game.service.TableService;
import com.jule.teenpatti.game.vavle.notice.NoticeBroadcastMessages;
import com.jule.teenpatti.log.service.LogReasons;
import io.netty.buffer.ByteBuf;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Slf4j
public class JoloGame_FullPressureShowReq_50065 extends ClientReq {
    private long time;
    private JoloGame.JoloGame_FullPressureShowReq req;

    public JoloGame_FullPressureShowReq_50065(int functionId) {
        super(functionId);
    }

    @Override
    public void readPayLoadImpl(ByteBuf buf) throws Exception {
        time = System.currentTimeMillis();
        byte[] blob = new byte[buf.readableBytes()];
        buf.readBytes(blob);
        req = JoloGame.JoloGame_FullPressureShowReq.parseFrom(blob);
        this.setTable(TableService.getInstance().getTable(header.gameId + "", req.getRoomId(), req.getTableId()));
    }

    @Override
    public void processImpl() throws Exception {
        try {
            log.debug("收到消息-> " + functionId + " reqNum-> " + header.reqNum + " " + req.toString());
            String userId = req.getUserId();
            String roomId = req.getRoomId();
            String tableId = req.getTableId();
            double betScore = req.getScore();

            JoloGame.JoloGame_FullPressureShowAck.Builder ack = JoloGame.JoloGame_FullPressureShowAck.newBuilder();
            ack.setUserId(userId);
            ack.setRoomId(roomId);
            ack.setTableId(tableId);
            ack.setSeatNum(0);
            ack.addAllHandCards(new ArrayList<>());
            ack.addAllMixedCards(new ArrayList<>());

            AbstractTable table = getTable();
            PlayerInfo player = table.getPlayer(userId);

            player.setAlreadyBetScore4Round(betScore); //修改玩家下注值
            player.setTotalAlreadyBetScore4Hand(player.getTotalAlreadyBetScore4Hand() + betScore);//累计玩家总得下注值
            table.accumulativeBet(player.getPlayerId(), betScore);
            //player.setPlayScoreStore(player.getPlayScoreStore() - betScore);//减去玩家桌面积分
            player.minusPlayScoreStore(betScore, LogReasons.CommonLogReason.GAME_SHOW);
            player.setCurChipsLose(player.getCurChipsLose() + betScore);
            player.setFullPressureShow(player.getIsBlind() == 1 ? 2 : 1);
            table.setTotalAlreadyBet(table.getTotalAlreadyBet() + betScore); //桌内累计下注金额
            //发送通知
            NoticeBroadcastMessages.moneyChangeNotice(table,userId,player.getPlayScoreStore());
            //广播玩家下注
            NoticeBroadcastMessages.betRoundDoBet(table, table.getCurrRoundId(), player, null,false);
            //发起孤注一掷通知
            NoticeBroadcastMessages.fullPressureShow(table,userId);
            Executors.newSingleThreadScheduledExecutor().schedule(()->fullPressureShow(table,player,ack),1500, TimeUnit.MILLISECONDS);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }finally {

        }
    }

    private void fullPressureShow(AbstractTable table,PlayerInfo player,JoloGame.JoloGame_FullPressureShowAck.Builder ack) {
        try {
            PlayerInfo winner = GameLogic.getWinner(table);
            if (winner != null && player != null) {
                if (winner.getPlayerId().equals(player.getPlayerId()) || table.getInGamePlayers().size() <= 2) {
                    int nextBetSeatNum = winner.getSeatNum();
                    while (true) {
                        if (nextBetSeatNum == table.getFirstBetSeatNum()) {
                            break;
                        }
                        nextBetSeatNum += 1;
                        if (nextBetSeatNum > 5) {
                            nextBetSeatNum = 1;
                        }
                        PlayerInfo playerInfo = table.getInGamePlayersBySeatNum().get(nextBetSeatNum);
                        if(playerInfo != null) {
                            table.getFullPressure().add(playerInfo);
                        }
                    }
                    //全部赢了则直接进入结算
                    GameLogic.settle(table);
                } else {
                    //修改玩家状态
                    player.setState(PlayerStateEnum.showfail);
                    table.setLastActionTime(System.currentTimeMillis());
                    table.getInGamePlayers().remove(player.getSeatNum()); //将玩家从游戏中移除
                    PlayerInfo nextActionPlayer = table.getNextBetPlayer(player.getSeatNum(), NextBetPlayerReasonEnum.FOLD);
                    if (nextActionPlayer == null) {
                        GameLogic.settle(table);
                    } else {
                        nextActionPlayer.setState(PlayerStateEnum.beting);//设置下一个玩家为行动状态
                        GameLogic.betTimer(table);//启动下一个玩家下注倒计时
                    }
                    NoticeBroadcastMessages.sideShowResult(table, null, player, nextActionPlayer);
                }
                ack.setSeatNum(player.getSeatNum());
                ack.setResult(1);
                ack.addAllHandCards(Ints.asList(player.getHandCards()));
                ack.addAllMixedCards(player.getMixedCardList() == null ? new ArrayList<>() : player.getMixedCardList());
                ctx.writeAndFlush(new JoloGame_FullPressureShowAck_50065(ack.build(), header));
            } else {
                log.error("孤注一掷比牌信息异常：winner == null? " + (winner == null) + " player == null?" + (player == null));
                ack.setResult(0);
                ack.setResultMsg("孤注一掷比牌信息错误！");
                ctx.writeAndFlush(new JoloGame_FullPressureShowAck_50065(ack.build(), header));
            }
        }catch (Exception e){
            log.error("孤注一掷定时任务错误！！！");
        }
    }
}
